package com.mspbots.core.wise.controller;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mspbots.core.AbstractBaseController;
import com.mspbots.core.RestMessageObject;
import com.mspbots.core.wise.model.TenantUser;
import com.mspbots.core.wise.model.TenantUserConfiguration;
import com.mspbots.core.wise.model.TenantUserWorkSchedule;
import com.mspbots.core.wise.model.Users;
import com.mspbots.core.wise.model.dto.TenantUserWorkScheduleDTO;
import com.mspbots.core.wise.service.TenantUserConfigurationService;
import com.mspbots.core.wise.service.TenantUserService;
import com.mspbots.core.wise.service.TenantUserWorkScheduleService;
import com.mspbots.core.wise.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("user-work-schedule")
public class TenantUserWorkScheduleController extends AbstractBaseController<TenantUserWorkSchedule, TenantUserWorkScheduleService> {

    @Autowired
    private TenantUserConfigurationService tenantUserConfigurationService;
    @Autowired
    private TenantUserService tenantUserService;
    @Autowired
    private UsersService usersService;

    @GetMapping("page-user")
    public Callable page(Page<TenantUserWorkScheduleDTO> page, TenantUserWorkSchedule queryParams) {
        return () -> service.userPage(page, queryParams);
    }

    @PostMapping(path = "save-batch")
    public Callable saveOrUpdateBatch(@RequestBody TenantUserWorkScheduleDTO tenantUserWorkScheduleDTO) {
        return () -> service.saveOneUser(tenantUserWorkScheduleDTO);
    }

    @PostMapping(path = "save-batch-users")
    public Callable saveOrUpdateBatchUsers(@RequestBody List<TenantUserWorkScheduleDTO> tenantUserWorkScheduleDTO) {
        return () -> service.saveBatchUsers(tenantUserWorkScheduleDTO);
    }

    @GetMapping(path = "fix")
    public Callable fix() {
        List<TenantUserConfiguration> list = tenantUserConfigurationService.list(Wrappers.<TenantUserConfiguration>lambdaQuery().eq(TenantUserConfiguration::getKeyword, "work_time"));
        List<Long> result = new ArrayList<>();
        AtomicInteger count = new AtomicInteger();
        list.forEach(item -> {
            TenantUser tenantUser = tenantUserService.getById(item.getTenantUserId());
            if (ObjectUtils.isNotEmpty(tenantUser) && StringUtils.isNotBlank(tenantUser.getEmail())) {
                Users users = usersService.getOne(Wrappers.<Users>lambdaQuery().eq(Users::getUsername, tenantUser.getEmail().toLowerCase()));
                if (ObjectUtils.isNotEmpty(users)) {
                    JSONObject jsonObject = JSONUtil.parseObj(item.getKeywordValue());
                    TenantUserWorkScheduleDTO tenantUserWorkScheduleDTO = new TenantUserWorkScheduleDTO();
                    tenantUserWorkScheduleDTO.setTenantId(users.getTenantId());
                    tenantUserWorkScheduleDTO.setUserId(users.getId());
                    tenantUserWorkScheduleDTO.setTimezoneFull(jsonObject.getStr("timezone"));
                    tenantUserWorkScheduleDTO.setTimezoneOffset(jsonObject.getStr("offset"));

                    String workTimesStr = jsonObject.getStr("workTimes");
                    List<JSONObject> workTimes = JSONUtil.toList(JSONUtil.parseArray(workTimesStr), JSONObject.class);
                    List<TenantUserWorkSchedule> workScheduleList = new ArrayList<>();
                    int i = 1;
                    for (JSONObject workTime : workTimes) {
                        TenantUserWorkSchedule work = TenantUserWorkSchedule.builder()
                                .tenantId(users.getTenantId())
                                .userId(users.getId())
                                .dayOff(true)
                                .dayOfWeek(workTime.getStr("day").toUpperCase())
                                .createTime(LocalDateTime.now())
                                .sort(i++)
                                .build();
                        if (StringUtils.isNotBlank(workTime.getStr("startTime"))) {
                            work.setBeginTime(LocalTime.parse(workTime.getStr("startTime")));

                        }
                        if (StringUtils.isNotBlank(workTime.getStr("endTime"))) {
                            work.setEndTime(LocalTime.parse(workTime.getStr("endTime")));
                        }

                        workScheduleList.add(work);
                    }
                    tenantUserWorkScheduleDTO.setWorkScheduleList(workScheduleList);
                    service.saveOneUser(tenantUserWorkScheduleDTO);
                    count.getAndIncrement();
                } else {
                    result.add(item.getTenantUserId());
                }
            } else {
                result.add(item.getTenantUserId());
            }
        });
        return () -> RestMessageObject.ok(list.size() + " " + count.get() + " " + result);
    }

    @GetMapping("findUserSchedule/{tenantId}")
    public Callable findUserSchedule(@PathVariable Long tenantId) {
        return () -> service.findUserSchedule(tenantId);
    }

}
